package cn.piesat.translate.service.impl;

import cn.piesat.translate.common.Constants;
import cn.piesat.translate.listener.StringExcelListener;
import cn.piesat.translate.service.ExcelOptionsService;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author tw
 * @Description excel操作
 * @Date 2022/8/3 10:46
 **/
@Service
public class ExcelOptionsServiceImpl implements ExcelOptionsService {

    private static Logger log = LoggerFactory.getLogger(ExcelOptionsServiceImpl.class);

    /**
     * 根据excel输入流，读取excel文件
     *
     * @param inputStream
     * @return
     */
    @Override
    public synchronized List<List<String>> readWithoutHead(InputStream inputStream) {
        List<List<String>> datas = null;
        try {
            long l = System.currentTimeMillis();
            StringExcelListener listener = new StringExcelListener();
            ExcelReader excelReader = EasyExcelFactory.read(inputStream, null, listener).headRowNumber(0).build();
            excelReader.readAll();
            datas = listener.getDatas();
            excelReader.finish();
            log.info("读取到文件" + datas.size() + "条数据，耗时" + (System.currentTimeMillis() - l) + " ms");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("读取excel文件异常" + e.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return datas;
    }

    /**
     * 处理数据
     *
     * @param lists
     * @return
     */
    @Override
    public synchronized Map<String, Integer> dealData(List<List<String>> lists, String nameKey) {
        long l = System.currentTimeMillis();
        Map<String, Integer> nameSumMap = new HashMap<>();
        if (lists.size() > 1) {
            //表头信息
            List<String> names = lists.get(0);
            int nameIndex = names.indexOf(nameKey);
            for (int i = 1; i < lists.size(); i++) {
                List<String> strings = lists.get(i);
                String name = strings.get(nameIndex).trim();
                if (StringUtils.isNotEmpty(name)) {
                    name = name.replaceAll("\n", "").replaceAll("\r", "").replaceAll("\t", "").trim();
                    if (name.contains(" ") || name.contains("\\s+") || name.contains("-") || name.contains("_") || name.contains("－")) {
                        String newName = name.replaceAll("\\s+", "-").replaceAll("_", "-").replaceAll("－", "-");
                        String[] split = newName.split("-");
                        for (String s : split) {
                            if (nameSumMap.containsKey(s)) {
                                nameSumMap.put(s, nameSumMap.get(s) + 1);
                            } else {
                                nameSumMap.put(s, 1);
                            }
                        }
                    }
                }
            }
            //排序
            nameSumMap = sortMap(nameSumMap);
        }
        log.info("原始数据" + lists.size() + "条，融合提取到" + nameSumMap.size() + "条数据，耗时" + (System.currentTimeMillis() - l) + "ms");
        return nameSumMap;
    }

    /**
     * 地名信息交换
     *
     * @param oriLists  原始文件交换
     * @param tranLists 翻译后文件
     * @param nameKey   地名标题
     * @return
     */
    @Override
    public synchronized List<List<String>> exchangeName(List<List<String>> oriLists, List<List<String>> tranLists, String nameKey) {
        //转换翻译文件
        Map<String, String> tranMap = exchangeTranData(tranLists);
        List<String> nameList = oriLists.get(0);
        int enameIndex = nameList.indexOf(nameKey);
        int cnameIndex = enameIndex + 1;
        //源文件加翻译字段信息
        nameList.add(cnameIndex, Constants.CNAME);
        StringBuilder builder = new StringBuilder();
        for (int i = 1; i < oriLists.size(); i++) {
            List<String> list = oriLists.get(i);
            String name = list.get(enameIndex);
            if (StringUtils.isNotEmpty(name)) {
                name = name.replaceAll("\n", "").replaceAll("\r", "").replaceAll("\t", "").trim();
                if (name.contains(" ") || name.contains("\\s+") || name.contains("-") || name.contains("_") || name.contains("－")) {
                    String newName = name.replaceAll("\\s+", "-").replaceAll("_", "-").replaceAll("－", "-");
                    String[] split = newName.split("-");
                    for (String s : split) {
                        String value = tranMap.get(s);
                        builder.append(value == null ? s : value);
                    }
                    list.add(cnameIndex, builder.toString());
                }
            }
            builder.delete(0, builder.length());
        }
        return oriLists;
    }

    /**
     * 将翻译后的文件转换为map类型
     *
     * @param tranLists
     * @return
     */
    private Map<String, String> exchangeTranData(List<List<String>> tranLists) {
        Map<String, String> tranMap = new HashMap<>(tranLists.size() - 1);
        for (int i = 1; i < tranLists.size(); i++) {
            List<String> list = tranLists.get(i);
            if (list.size() == 3) {
                tranMap.put(list.get(0), list.get(2));
            }
        }
        return tranMap;
    }


    /**
     * 排序
     *
     * @param map
     * @return
     */
    private Map<String, Integer> sortMap(Map<String, Integer> map) {
        //利用Map的entrySet方法，转化为list进行排序
        List<Map.Entry<String, Integer>> entryList = new ArrayList<>(map.entrySet());
        //利用Collections的sort方法对list排序
        entryList.sort((o1, o2) -> {
            //正序排列，倒序反过来
            return o2.getValue() - o1.getValue();
        });
        LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<String, Integer>();
        for (Map.Entry<String, Integer> e : entryList) {
            linkedHashMap.put(e.getKey(), e.getValue());
        }
        return linkedHashMap;
    }


    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("112");
        list.add("eeee");
        list.add(0, "abccc");
        System.out.println();
    }
}
